<template>
    <div class="added">
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="140px" class="demo-ruleForm">
            <el-row :gutter='20' class="container" style='margin: initial'>
                <el-col :span="8">
                    <el-form-item label="养殖批次号：" prop="batch" required>
                        <el-input placeholder="请输入内容" v-model="ruleForm.batch" style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="养殖方式：" prop="way">
                        <el-select allow-create filterable default-first-option v-model="ruleForm.way" placeholder="" style="width:300px">
                            <el-option  v-for="item in plantingwway" :key="item.id" :label="item.name" :value="item.name">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="开始时间：" prop="plantTime">
                        <el-date-picker style="width:300px" v-model="ruleForm.plantTime" @change="gettime"
                                        value-format="yyyy/MM/dd" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="预计产出量：">
                        <el-input placeholder="请输入内容" v-model="ruleForm.expOutPutsAcresNumber" style="width:300px">
                            <template slot="suffix">kg</template>
                        </el-input>
                    </el-form-item>
<!--                    <el-form-item label="基原名称：" prop="jyName">-->
<!--                        <el-select v-model="ruleForm.jyName" @change="getjy" value-key="id" placeholder=""-->
<!--                            style="width:300px">-->
<!--                            <el-option v-for="item in baselist" :key="item.id" :label="item.name"-->
<!--                                :value="item">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种苗照片：">-->
<!--                        <el-upload class="upload-poster" action="https://jsonplaceholder.typicode.com/posts/"-->
<!--                            :show-file-list="false" :on-change="imgPreview" :auto-upload="false">-->
<!--                            <img v-if="plantImg" :src="plantImg" class="avatar">-->
<!--                            <i v-else class="el-icon-circle-plus avatar-uploader-icon"></i>-->
<!--                            <div style="color: #1BC46D;">jpg、png、gif格式，60x60像素，不超过2MB</div>-->
<!--                        </el-upload>-->
<!--                    </el-form-item>-->

<!--                    <el-form-item label="种苗数量：" prop="plantNumber">-->
<!--                        <el-input placeholder="请输入" v-model="ruleForm.plantNumber" style="width: 200px">-->
<!--                            <template slot="append">-->

<!--                                <el-select v-model="ruleForm.units" placeholder="单位" style="width:80px !important">-->
<!--                                    <el-option v-for="item in unitList" :key="item.id" :label="item.name"-->
<!--                                        :value="item.name">{{ item.name }}</el-option>-->
<!--                                </el-select>-->
<!--                            </template>-->
<!--                        </el-input>-->
<!--                        <el-button style="margin-left:10px" @click="gounit">单位管理</el-button>-->
<!--                    </el-form-item>-->
                </el-col>
                <el-col :span="8">
                    <el-form-item label="基地：" prop="plantBaseName">
                        <el-select v-model="ruleForm.plantBaseName" @change="getjd" value-key="id" placeholder="" style="width:300px">
                            <el-option v-for="item in subordinateBase" :key="item.id" :label="item.name" :value="item">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地块：" prop="soilName">
                        <el-select v-model="ruleForm.soilName" @change="getdk" placeholder="" value-key="id"
                            style="width:300px">
                            <el-option v-for="item in soilList" :key="item.id" :label="item.name"
                                :value="item">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
<!--                    <el-form-item label="地块：" prop="soilName">-->
<!--                        <el-select v-model="ruleForm.soilName"  @change="getdk" placeholder="" value-key="id"-->
<!--                            style="width:300px">-->
<!--                            <el-option v-for="item in landList" :key="item.id" :label="item.name"-->
<!--                                :value="item">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
                    <el-form-item label="种源：" prop="seed">
                        <el-select v-model="ruleForm.seed" @change="getjy" value-key="id" placeholder="" style="width:300px">
                            <el-option v-for="item in SeedList" :key="item.id" :label="item.jyName+' '+'批次：'+item.batch" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
<!--                    <el-form-item label="前茬作物：">-->
<!--                        <el-input placeholder="请输入内容" v-model="ruleForm.prevPlant" style="width:300px"></el-input>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="单位：" required>-->
<!--                        <el-select v-model="ruleForm.units" placeholder="" style="width:300px">-->
<!--                            <el-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.name">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种苗名称：" prop="plantName">-->
<!--                        <el-input placeholder="请输入内容" v-model="ruleForm.plantName" style="width:300px"></el-input>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种苗来源：" prop="source">-->
<!--                        <el-select v-model="ruleForm.source" placeholder="" style="width:300px">-->
<!--                            <el-option v-for="item in sourcelist" :key="item.id" :label="item.name"-->
<!--                                :value="item.name">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种苗企业：" v-if="ruleForm.source == '自购'">-->
<!--                        <el-select v-model="ruleForm.company" placeholder="" style="width:300px">-->
<!--                            <el-option v-for="item in supplierlist" :key="item.id" :label="item.supplierName"-->
<!--                                :value="item.supplierName">{{ item.supplierName }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种植方式：" prop="way">-->
<!--                        &lt;!&ndash; <el-input placeholder="请输入内容" v-model="ruleForm.way" style="width:300px">-->
<!--                            </el-input> &ndash;&gt;-->
<!--                        <el-select v-model="ruleForm.way" placeholder="" style="width:300px">-->
<!--                            <el-option v-for="item in plantingwway" :key="item.id" :label="item.name"-->
<!--                                :value="item.name">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种植基地：" prop="plantBaseName">-->
<!--                        <el-select v-model="ruleForm.plantBaseName" @change="getjd" value-key="id" placeholder=""-->
<!--                            style="width:300px">-->
<!--                            <el-option v-for="item in subordinateBase" :key="item.id" :label="item.name"-->
<!--                                :value="item">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="所属地块：" prop="soilName">-->
<!--                        <el-select v-model="ruleForm.soilName" @change="getdk" placeholder="" value-key="id"-->
<!--                            style="width:300px">-->
<!--                            <el-option v-for="item in soilList" :key="item.id" :label="item.name"-->
<!--                                :value="item">{{ item.name }}</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                    <el-form-item label="种植面积：" prop="plantArea">-->
<!--                        <el-input placeholder="请输入内容" v-model="ruleForm.plantArea" style="width:200px">-->
<!--                        </el-input>-->
<!--                        <span style="margin-left:20px;">亩</span>-->
<!--                    </el-form-item>-->


                </el-col>
                <el-col :span="8">
<!--                    <el-form-item label="地块面积：">-->
<!--                        <el-input placeholder="" v-model="ruleForm.area" style="width:250px" disabled>-->
<!--                        </el-input>-->
<!--                        <span style="margin-left:20px;">亩</span>-->
<!--                    </el-form-item>-->
                    <el-form-item label="养殖规模：" prop="plantArea">
                        <el-input placeholder="请输入规格" v-model="ruleForm.plantArea" style="width:250px">
                        </el-input>
                        <span style="margin-left:20px;">张</span>
                    </el-form-item>
<!--                    <el-form-item label="类型：" prop="type">-->
<!--                        <el-select v-model="ruleForm.type" placeholder="选择" style="width:300px !important">-->
<!--                            <el-option v-for="item in typeList" :key="item" :label="item" :value="item"></el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
                    <el-form-item label="负责人：" prop="plantUserName">
                        <el-select v-model="ruleForm.plantUserName" @change="getuser" value-key="id" placeholder="" style="width:222px !important">
                            <el-option v-for="item in userAll" :key="item.id" :label="item.name" :value="item">{{ item.name }}</el-option>
                        </el-select>
                        <el-button style="margin-left:10px" @click="gouser">养殖人</el-button>
                    </el-form-item>
                </el-col>
                <!--       产品说暂时不要用每个管理的用工记录 sameki 2024.6.3       -->
<!--                <el-col style='padding: 10px 0'>-->
<!--                    <h3 style='margin: 20px 0'>用工记录</h3>-->
<!--                    <el-upload-->
<!--                        style='float: left'-->
<!--                        class="upload-daoru"-->
<!--                        ref="upload"-->
<!--                        action=""-->
<!--                        :on-change="importExcel"-->
<!--                        accept=".xlsx,.xls"-->
<!--                        :show-file-list='false'-->
<!--                        :auto-upload="false">-->
<!--                        <el-button class='theme-button' slot="trigger" size="small">导入</el-button>-->
<!--                    </el-upload>-->
<!--                    <el-button class='theme-button' style='float: left' @click='downloadTemplate'>下载导入模板</el-button>-->
<!--                </el-col>-->
<!--                <el-col>-->
<!--                    <h4 v-if='hasFile'>{{ruleForm.file.name}}</h4>-->
<!--                </el-col>-->
            </el-row>
            <el-form-item class="footerFixed" label-width="0px">
                <div class='fixed'>
                    <el-button class='theme-button' @click="submitrule('ruleForm')">提交</el-button>
                    <el-button @click="backPage">返回</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
/*** 本狗屎页面并非本人所写，如果看到git是我的名字，那也只是看不惯之前的代码排版，格式了一下缩进 2024.5.18 sameki ***/
import {
    unit_findByList,
    user_findByAll,
    supplier_findByAll,
    plot_findByAll,
    model_crop_loadbind,
    addPlant,
    getAllPlantSeed,
    getlands
} from '@/request/api';
import { soil_findByBaseId } from '@/request/breedApi'
import axios from 'axios';
export default {
    data() {
        return {
            hasFile:false,
            soilId: '',
            plotlist: [],
            plantingwway: [
                { name: '精养' },
                { name: '套养' },
                { name: '散养' },
            ],
            sourcelist: [
                { name: "自购" },
                { name: '栽培' },
                { name: '野生移栽' }
            ],
            subordinateBase: [

            ],
            supplierlist: '',
            baselist: '',
            landList:[],
            userAll: '',
            typeList:['育苗','种植'],
            SeedList: [],//种源列表
            unitList: [],
            labelPosition: 'right',
            ruleForm: {
                seed:'',//种源
                seedName:'',//种源名称
                expOutPutsAcresNumber:'',//预计产出亩
                area:"",//地块面积
                prevPlant:'',//前茬作物
                type:'',//类型
                plantBaseName: '',//基地名称
                plantNumber: '',//种植编号
                plantName: '',//种植作物
                source: '',//来源
                way: '',//种植方式
                soilName1:"",//村级地块
                soilId1:"",//村级地块id
                soilName: '',//所属地块
                soilId:"",//地块id
                plantArea: '',//种植面积
                batch: '',//种植批次号
                plantUserName: '',//种植人
                plantTime: '',//种植时间
            },
            plantImg: '',
            rules: {
                jyName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantBaseName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantNumber: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantName: [{ required: true, message: '不能为空', trigger: 'change' }],
                source: [{ required: true, message: '不能为空', trigger: 'change' }],
                way: [{ required: true, message: '不能为空', trigger: 'change' }],
                soilName1: [{ required: true, message: '不能为空', trigger: 'change' }],
                soilName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantArea: [{ required: true, message: '不能为空', trigger: 'change' }],
                batch: [{ required: true, message: '不能为空', trigger: 'blur' }],
                plantUserName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
                reapTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
                type: [{ required: true, message: '不能为空', trigger: 'blur' }],
                seed: [{ required: true, message: '不能为空', trigger: 'blur' }],

            },
            soilList: ''
        }
    },
    watch:{
        'ruleForm.file'(val){
            if(val){
                this.hasFile = true
            }else{
                this.hasFile = false
            }
        }
    },
    mounted() {
        this.init()

    },
    methods: {
        //查询种源
        async selectSeedList() {
           const res = await getAllPlantSeed()
            if(res.code == 200){
                // console.log(res);
                this.SeedList = res.data
            }
        },
        //下载导入模板
        async downloadTemplate() {
            axios.get(localStorage.getItem('requestUrl')+'/labor/exportLaborTemplate?type=2',{responseType:'arraybuffer'}).then(res=>{
                console.log(res);
                const blob = new Blob([res.data],{type:'application/vnd.ms-excel'})
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download','种植导入模板.xlsx')
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(url)
                this.$notify({
                    title: '操作成功',
                    message: '下载成功',
                    type: 'success'
                })
            })
        },
        importExcel(file){
            console.log(file);
            this.ruleForm.file = file.raw
            this.$notify({
                title: '操作成功',
                message: '导入成功',
                type: 'success'
            })
            this.hasFile = true
        },
        //用工详情
        handleClick(params){
            this.dialogTitle = params.workBatch
            this.dialogTableVisible = true
        },
        //生成批号
        getBatch(){
            var num = ""
            for (var i = 0; i < 5; i++) {
                num += Math.floor(Math.random() * 10);
            }
            var mydate = new Date()
            var year = mydate.toLocaleDateString()
            var date = year.replace(/\//g, "");
            this.ruleForm.batch = date + num
        },
        gettime() {
            if (this.ruleForm.plantTime != "" && this.ruleForm.reapTime != "") {
                var oDate1 = new Date(this.ruleForm.plantTime)
                var oDate2 = new Date(this.ruleForm.reapTime)
                if (oDate1 > oDate2) {
                    this.$notify({
                        title: '提示',
                        message: '采购时间不得早于生产时间',
                        type: 'info'
                    });
                    this.ruleForm.plantTime = ""
                    this.ruleForm.reapTime = ""
                }
            }
        },
        gounit() {
            this.$router.push({
                path: '/unit'
            })
        },
        gouser() {
            this.$router.push({
                path: '/staffsManagement/addedstaff'
            })
        },
        init() {
            this.selectSeedList()
            unit_findByList("").then((res) => {
                this.unitList = res.data
            })
            user_findByAll("").then((res) => {
                this.userAll = res.data
            })
            // model_crop_loadbind("").then((res) => {
            //     this.baselist = res.data
            // })
            // basesource_findByAll("").then((res)=>{
            //     this.baselist = res.data
            // })
            supplier_findByAll("").then((res) => {
                this.supplierlist = res.data
            })

            // base_findByAll("").then((res)=>{
            //     this.subordinateBase = res.data
            // })
            //获取所有基地
            plot_findByAll().then((res) => {
                this.subordinateBase = res.data
            })
            this.getBatch()
        },
        getjy(ele) {
            console.log(ele);
            this.ruleForm.jyId = ele.jyId
            this.ruleForm.jyName = ele.jyName
            // this.ruleForm.seedId = ele.jyId
        },
       async getdk1(ele) {
            this.ruleForm.soilName1 = ele.name
            let res= await  getlands(ele.id)
            this.landList = res.data
           console.log(this.landList);
        },
        getdk(ele) {
            console.log(ele)
            this.ruleForm.soilId = ele.id
            this.ruleForm.soilName = ele.name
            this.ruleForm.area = ele.area
        },
        getjd(ele) {
            this.soilId = ''
            this.ruleForm.plantBaseId = ele.id
            this.ruleForm.plantBaseName = ele.name
            soil_findByBaseId(`${ele.id}/2`).then((res) => {
                // console.log(res)
                this.soilList = res
            })
        },
        getuser(ele) {
            this.ruleForm.plantUserId = ele.id
            this.ruleForm.plantUserName = ele.name
        },
        imgPreview(file, fileList) {
            this.plantImg = URL.createObjectURL(file.raw);
            let fileName = file.name;
            let regex = /(.jpg|.gif|.png|.jpeg)$/;
            if (regex.test(fileName.toLowerCase())) {
                this.ruleForm.files = file.raw
                this.ruleForm.plantImg = file.name
            } else {
                this.$message.error('请选择图片文件');
            }
        },
        submitrule(formName) {
            // console.log(this.ruleForm)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // if(this.ruleForm.area<this.ruleForm.plantArea){
                    //     this.$notify({
                    //         title: '提示',
                    //         message: '种植面积不能大于地块面积',
                    //         type: 'info'
                    //     });
                    //     this.ruleForm.plantArea=""
                    //     return false
                    // }
                    // if (this.ruleForm.units == "" || this.ruleForm.units == undefined) {
                    //     this.$notify({
                    //         title: '提示',
                    //         message: '种苗数量单位不能为空',
                    //         type: 'info'
                    //     });
                    //     return false
                    // }
                    this.$confirm('请仔细核对所填信息，提交后不能修改！', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.ruleForm.seedId = this.ruleForm.seed.id
                        this.ruleForm.seedName = this.ruleForm.seed.jyName
                        delete this.ruleForm.seed
                        console.log(this.ruleForm)
                        let formdata = new FormData()
                        for (var a in this.ruleForm) {
                            if (this.ruleForm[a] == null || this.ruleForm[a] == 'null') {
                                this.ruleForm[a] = '';
                                formdata.append(a, '');
                            } else {
                                formdata.append(a, this.ruleForm[a]);
                            }
                        }
                        addPlant(formdata).then((res) => {
                            this.$notify({
                                title: '操作成功',
                                message: '保存成功',
                                type: 'success'
                            });
                            this.$router.push({
                                path: '/plant'
                            })
                            this.init()
                        })
                    })
                } else {
                    return false
                }
            })
        },
        backPage() {
            this.$router.go(-1)
        }
    }
}
</script>

<style lang='less' scoped>
/deep/.upload-daoru {

    .el-upload {
        border: none;
        width: auto;
        height: auto;
        border-radius: 0;
        float: right;
        margin-right: 10px;
    }
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 180px;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.el-upload--text {
    width: 180px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 90px;
    /* height: 178px; */
    line-height: 140px;
    text-align: center;
    color: #1BC46D;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style lang="less">

.added {
    .el-input .el-input__inner {
        background-color: #FAFAFA !important;
        border: 1px solid #EEEEEE !important;
    }

    .el-textarea__inner {
        background-color: #FAFAFA !important;
        border: 1px solid #EEEEEE !important;
    }
}
</style>
